package com.example.demo.RabbitMq;


import com.rabbitmq.client.Channel;
import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

import static com.example.demo.RabbitMq.RabbitConfig.EMAIL_QUEUE;

@Component
public class EmailConsumer {

    @Autowired
    private JavaMailSender mailSender;

    @Autowired
    private RabbitTemplate rabbitTemplate;


    // 临时调试：打印原始消息内容
//    @RabbitListener(queues = EMAIL_QUEUE)
//    public void handleEmailMessage(EmailMessage emailMessage) {
//        System.out.println("原始消息：" +emailMessage.toString()); // 查看JSON格式是否正确
//    }


    // 监听邮件队列，接收消息并发送邮件
    @RabbitListener(queues = EMAIL_QUEUE)
    public void handleEmailMessage(EmailMessage emailMsg, Channel channel, Message message) throws MessagingException, IOException {
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        boolean isConfirmed = false; // 确认状态标志
        try {
            System.out.println("接收到邮件消息：" + emailMsg.getMessageId());

            // 1. 构建邮件
            MimeMessage mimeMessage = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
            helper.setTo(emailMsg.getTo()); // 收件人
            helper.setSubject(emailMsg.getSubject()); // 主题
            helper.setText(emailMsg.getContent(), true); // 内容（第二个参数true表示支持HTML）
            helper.setFrom("15628479336@163.com", emailMsg.getFromName()); // 发件人（需与配置文件一致）
            // 2. 发送邮件
            mailSender.send(mimeMessage);
            System.out.println("邮件发送成功：" + emailMsg.getMessageId());
            // 3. 手动ACK（确认消息处理完成，RabbitMQ可删除消息）
            channel.basicAck(deliveryTag, isConfirmed);
            isConfirmed = true;
            System.out.println("消息确认完成：" + deliveryTag);

        } catch (Exception e) {
            System.out.println("邮件发送失败，消息ID：" + emailMsg.getMessageId() + "，原因：" + e.getMessage());
            // 3. 未确认过才拒绝
            if (!isConfirmed) {
                try {
                    // 拒绝并转发到死信队列（避免重复消费）
                    channel.basicNack(deliveryTag, false, false);
                    isConfirmed = true;
                } catch (Exception ex) {
                    System.err.println("NACK失败，deliveryTag: " + deliveryTag);
                }
            }
        } finally {
            System.out.println("邮件发送结束，消息ID：" + emailMsg.getMessageId());
        }
}
}
